<template>
    <div>
        <div :class='$style.pageContainer'>
            <el-card :class='$style.menu'>
                <template #header>
                    菜单
                </template>
                <div>
                    <el-tree node-key='id' ref='treeRef' :props='treeDefaultProps' :data='menuData' @node-click='nodeClick'>
                        <template #default='{ node, data }'>
                            <div :class='$style.treeNode'>
                                <span :class='$style.label'>{{ node.label }}</span>
                                <div :class='$style.append'>
                                    <!-- <el-icon><Plus /></el-icon> -->
                                    <XRequestButton isConfirm confirmText='确定删除该菜单吗' :click='async () => deleteSingleMenu(data.id)'>
                                        <el-icon class='m-l-10'><Delete /></el-icon>
                                    </XRequestButton>
                                    
                                </div>
                            </div>
                        </template>
                    </el-tree>
                </div>
            </el-card>
            <el-card :class='$style.params'>
                <template #header>
                    {{menuFormData.id ? '编辑' : '新增'}}
                </template>
                <el-form ref='menuFormRef' :model='menuFormData' :rules='menuRules' label-width='100px' size='small'>
                    <el-form-item label='上级菜单' prop='parentId' :rules='[{required : false}]'>
                        <el-cascader class='w-100' :disabled='menuFormData.id !== ""' v-model.number='menuFormData.parentId' :options='[{name : "根菜单", id : 0}, ...menuData]' :props='{value : "id", checkStrictly : true, emitPath : false, label : "name", children : "children"}'></el-cascader>
                    </el-form-item>
                    <el-form-item label='菜单名' prop='name'>
                        <el-input type='text' clearable show-word-limit :maxlength='menuRules.name[1].max' v-model='menuFormData.name' />
                    </el-form-item>
                    <el-form-item label='路径' prop='path'>
                        <el-input type='text' clearable show-word-limit :maxlength='menuRules.path[1].max' v-model='menuFormData.path' />
                    </el-form-item>
                    <el-form-item label='组件' prop='component'>
                        <el-input type='text' clearable show-word-limit :maxlength='menuRules.component[1].max' v-model='menuFormData.component' />
                    </el-form-item>
                    <el-form-item label='排序' prop='sort' :rules='[{required : false}]'>
                        <el-input type='text' clearable v-model.number='menuFormData.sort'></el-input>
                    </el-form-item>
                    <el-form-item label='展示' prop='display' :rules='[{required : false}]'>
                        <el-switch v-model='menuFormData.display' />
                    </el-form-item>
                    <el-form-item label='KEEP ALIVE' prop='keepAlive' :rules='[{required : false}]'>
                        <el-switch v-model='menuFormData.keepAlive' />
                    </el-form-item>
                    <div style='display:none'>
                        <el-form-item label='id' prop='id' :rules='[{required : false}]'>
                            <el-input type='hidden' clearable v-model.number='menuFormData.id'></el-input>
                        </el-form-item>
                    </div>
                    <el-form-item>
                        <el-button @click='resetMenuForm'>重 置</el-button>
                        <XRequestButton class='m-l-10' :click='saveMenu'>
                            <el-button type='primary'>确 定</el-button>
                        </XRequestButton>
                    </el-form-item>
                </el-form>
            </el-card>
            <el-card v-if='currentMenuId != 0' :class='$style.pageRules'>
                <template #header>
                    权限
                </template>
                <Permission :menuId='currentMenuId'></Permission>
            </el-card>
        </div>
    </div>


    <!-- <el-dialog destroy-on-close v-model='dialogVisible' width='400px'>
        <Permission></Permission>
        <template #footer>
            <el-button size='mini' @click='dialogVisible=false'>取 消</el-button>
            <XRequestButton class='m-l-20'>
                <el-button size='mini' type='primary'>确 定</el-button>
            </XRequestButton>
        </template>
    </el-dialog> -->

</template>

<script lang='ts' setup>
    import { Delete, Plus } from '@element-plus/icons'
    import Permission from './Permission.vue'
    import { ElMessage } from "element-plus";
    import { computed, nextTick, reactive, ref } from "vue";
    import { useStore } from "vuex";
    import { addMenuApi, deleteMenuApi, editMenuApi } from '../../../api/menu'
    import { filterEmpty } from "../../../utils";

    const $store = useStore()

    const dialogVisible = ref(true)

    const treeDefaultProps = {
        children: 'children',
        label: 'name'
    }
    const treeRef = ref()
    const menuFormRef = ref()
    const menuData = computed(() => $store.state.menu.menus)
    const currentMenuId = ref(0)


    const menuFormData = reactive({
        id : '',
        parentId : 0,
        name : '',
        path : '',
        component : '',
        keepAlive : true,
        display : true,
        sort : 0,
    })

    const menuRules = reactive<{[key in keyof (typeof menuFormData)]?:any[]}>({
        name : [
            {
                required : true,
                message : '请输入菜单名'
            },
            {
                min : 2,
                max : 10,
                message: '菜单名长度在2-10个字符之间',
            }
        ],

        path : [
            {
                required : true,
                message : '请输入路径'
            },
            {
                max : 30,
                message: '路径长度不能超过30个字符',
            }
        ],

        component : [
            {
                required : true,
                message : '请输入组件'
            },
            {
                max : 30,
                message: '组件长度不能超过30个字符',
            }
        ],
    })

    async function saveMenu() {
        try {
            await menuFormRef.value.validate()
            
            let data:{[key in keyof (typeof menuFormData)]? : any} = {...menuFormData}
            data.keepAlive = Number(data.keepAlive)
            data.display = Number(data.display)
            filterEmpty(data)
            const res = await (data.id ? editMenuApi(data.id, data) : addMenuApi(data))
            if(res.success) {
                ElMessage.success('保存成功')
                resetMenuForm()
                $store.dispatch('getPermissionResource')
            }else {
                ElMessage.error!(res.msg)
            }

        } catch (error) {
            console.log(error)
        }
    }
    
    function resetMenuForm() {
        menuFormRef.value.resetFields()
        nextTick(() => {
            menuFormRef.value.clearValidate()
        })
    }

    function nodeClick(data:{[key in keyof (typeof menuFormData)] : any}) {
        currentMenuId.value = data.id
        menuFormData.id = data.id
        menuFormData.parentId = data.parentId
        menuFormData.name = data.name
        menuFormData.path = data.path
        menuFormData.component = data.component
        menuFormData.sort = data.sort
        menuFormData.display = data.display == 1
        menuFormData.keepAlive = data.keepAlive == 1
    }

    async function deleteSingleMenu(id:number) {
        const res = await deleteMenuApi(id)
        if(res.success) {
            if(currentMenuId.value == id) {
                currentMenuId.value = 0
            }
            ElMessage.success!('删除成功')
            $store.dispatch('getPermissionResource')
        }else {
            ElMessage.error!(res.msg)
        }
    }

</script>

<style scoped module lang='scss'>
    .pageContainer{
        display: flex;
        gap : 10px;

        .menu {
            width: 300px;
        }

        .params {
            width: 500px;
        }

        .pageRules{
            flex: 1;
        }
    }

    .treeNode{
        display: flex;
        align-items: center;
        flex: 1;

        .label{
            flex: 1;
        }

        .append{
            display: none;
        }

        &:hover{
            .append{
                display: block;
            }
        }
    }
</style>